package com.mobartisan.workinglunch.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.bean.globalSetting;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.listener.CallBackListenter;
import com.mobartisan.workinglunch.network.action.SnakeAction;
import com.mobartisan.workinglunch.ui.fragment.PersonFragment;
import com.mobartisan.workinglunch.util.AndroidUtils;
import com.mobartisan.workinglunch.util.FileUtil;
import com.mobartisan.workinglunch.util.ObjectUtils;
import com.mobartisan.workinglunch.util.ToastUtils;
import com.orhanobut.logger.Logger;

import java.io.File;

import okhttp3.ResponseBody;
import rx.Subscriber;


public class CheckVersionThread {
    private Context context = null;
    private PackageInfo info = null;
    private String localPath;
    private CallbackAction2<Boolean, String> callback = null;
    private CallBackListenter callBackListenter;
    private globalSetting appUpdateBean = null;
    private String url = "https://www.pgyer.com/apiv1/app/install?aId=607cc75e0ad15db800b430f56d6de0d1&_api_key=f2dc44eeac000e437bc9de7f6844b87b";

    public CheckVersionThread(Context context, globalSetting appUpdateBean, CallBackListenter callBackListenter) {
        this.context = context;
        this.appUpdateBean = appUpdateBean;
        this.callBackListenter = callBackListenter;
        try {
            info = this.context.getPackageManager().getPackageInfo(this.context.getPackageName(), 0);
            Logger.d("info.versionName:" + info.versionName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void checkServerVersion() {

    }

    public void compareVersionCode() {
        String[] serverVersionArr = ObjectUtils.getSeparatedItems(appUpdateBean.getCurrentversion(), '.');
        String[] currentVersionArr = ObjectUtils.getSeparatedItems(info.versionName, '.');
        String serverVersionArr1 = "0";
        String serverVersionArr2 = "0";
        String serverVersionArr3 = "0";
        String serverVersionArr4 = "0";
        for (int i = 0; i < serverVersionArr.length; i++) {
            if (i == 0) {
                serverVersionArr1 = serverVersionArr[i];
            } else if (i == 1) {
                serverVersionArr2 = serverVersionArr[i];
            } else if (i == 2) {
                serverVersionArr3 = serverVersionArr[i];
            } else if (i == 3) {
                serverVersionArr4 = serverVersionArr[i];
            }
        }
        if (!ObjectUtils.equals(serverVersionArr1, currentVersionArr[0])) {
            // 大版本不同，需要强制更新
            Constants.isChickVersion= true;
            onClickVersion();
            if (SnakeApplication.mainActivity != null) {
                SnakeApplication.mainActivity.handler.sendEmptyMessage(0);
                PersonFragment.getFragmetntA().handler.sendEmptyMessage(1);
                Constants.isNewest = true;
            }
            updateDialog(true);
        } else if (!ObjectUtils.equals(serverVersionArr3, currentVersionArr[2]) || !ObjectUtils.equals(serverVersionArr2, currentVersionArr[1])) {
            // 小版本，不需要强制更新，但是需要弹出更新提示框
            Constants.isChickVersion= true;
            onClickVersion();
            if (SnakeApplication.mainActivity != null) {
                SnakeApplication.mainActivity.handler.sendEmptyMessage(0);
                PersonFragment.getFragmetntA().handler.sendEmptyMessage(1);
                Constants.isNewest = true;
            } else {
                SnakeApplication.loginActivity.handler.sendEmptyMessage(2);
                Constants.isNewest = true;
            }
            updateDialog(false);
        } else {
            Constants.isChickVersion= false;
            onClickVersion();
            ToastUtils.showShort("当前已是最新版本。");
        }
    }

    private void onClickVersion() {
        if (callBackListenter != null)
            callBackListenter.onCallBack();
    }

    private boolean isfalg;

    public void setVersionFlag(boolean isfalg) {
        this.isfalg = isfalg;
    }

    /**
     * ：更新对话框 Author:dell
     *
     * @2015年7月20日 @下午4:00:38
     * @param isShouldUpdate
     * 是否需要强制更新 void
     */
    private Dialog dialog = null;

    public void updateDialog(final boolean isShouldUpdate) {

        dialog = new Dialog(context, R.style.mystyle);
        SnakeApplication.dialog = dialog;
        dialog.setContentView(R.layout.dialog_update_version);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CLIP_HORIZONTAL | Gravity.CENTER_VERTICAL);
        TextView tv_cancel = (TextView) dialogWindow.findViewById(R.id.tv_cancel);
        TextView content_tv = (TextView) dialogWindow.findViewById(R.id.content_tv);
        TextView tv_confirm = (TextView) dialogWindow.findViewById(R.id.tv_confirm);
        if (isShouldUpdate)
            content_tv.setText("检测到新版本(V" + appUpdateBean.getCurrentversion() + "),请立即更新，否则你将无法使用此APP");
        else
            content_tv.setText("检测到新版本(V" + appUpdateBean.getCurrentversion() + "),您需要升级吗？");
        // 更新内容
        TextView message_content = (TextView) dialogWindow.findViewById(R.id.message_content);
        message_content.setVisibility(View.GONE);
        tv_cancel.setOnClickListener((v) -> {
            dialog.dismiss();
            if (isShouldUpdate)
                SnakeApplication.getInstance().exitApp();
        });
        tv_confirm.setOnClickListener((v) -> {
            dialog.dismiss();
            onDownloadUpdate(isShouldUpdate);
        });
        lp.width = LayoutParams.MATCH_PARENT; // 宽度
        lp.height = LayoutParams.WRAP_CONTENT; // 高度
        dialogWindow.setAttributes(lp);
        dialog.show();
    }


    protected void onDownloadUpdate(boolean isShouldUpdate) {
        DownloadFilePopupDialog downloadFilePopupDialog = new DownloadFilePopupDialog(this.context);
        localPath = FileUtil.getAvaiableFilePath(context, "downLoadApp", info.packageName + ".apk");
        File file = new File(localPath);
        if (FileUtil.isExists(file)) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageArchiveInfo(localPath, PackageManager.GET_ACTIVITIES);
            if (packageInfo.versionName == null) {
                FileUtil.deleteFile(file);
                loadApk(isShouldUpdate, downloadFilePopupDialog, file);
            } else {
                if (packageInfo.versionName.equals(appUpdateBean.getCurrentversion()) && !packageInfo.versionName.equals(info.versionName)) {
                    onDownloadSuccess();
                } else {
                    loadApk(isShouldUpdate, downloadFilePopupDialog, file);
                }
            }
        } else {
            loadApk(isShouldUpdate, downloadFilePopupDialog, file);
        }
    }

    private void loadApk(boolean isShouldUpdate, DownloadFilePopupDialog downloadFilePopupDialog, final File file) {
        downloadFilePopupDialog.init("下载更新", isShouldUpdate, url, localPath, new CallbackAction<Boolean>() {
            @Override
            public void doAction(Boolean args) {
                if (!args) {
                    FileUtil.deleteFile(file);
                } else
                    onDownloadSuccess();
            }
        });
        downloadFilePopupDialog.startDownload();
    }

    protected void onDownloadSuccess() {
        AndroidUtils.installApk(this.context, this.localPath);
    }

    /**
     * 判断弹出框是否展开
     *
     * @return
     */
    public boolean isShowDialog() {
        if (null != dialog && dialog.isShowing())
            return true;
        return false;
    }

}
